//
//  UserCenterPageController.swift
//  Exchange
//
//  Created by rui on 2018/5/22.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class UserCenterPageController: TabbarPageController {
    
    let kTradeUserStyleOneCell = "TradeOrderUserCenterOneCell"
    let kTradeUserStyleTwoCell = "TradeOrderUserCenterTwoCell"
    
    lazy var emptyView: EmptyView = {
        let empty = EmptyView()
        empty.message = kText("暂无相关数据")
        return empty
    }()
    
    lazy var viewModel:TradeOrderUserCenterViewModel = {
        let vm = TradeOrderUserCenterViewModel()
        vm.response = {[weak self](state,isSuccess,errorMsg)in
            if state == ResponseState.trade_order_related || state == ResponseState.trade_ad_user  {
                if isSuccess {
                    //刷新头部信息
                    self?.tableView.reloadData()
                }else {
                    if let msg = errorMsg {
                        CYMBShow.showMessage(msg)
                    }else {
                        CYMBShow.showMessage(kText("当前无网络,请检查网络"))
                    }
                }
                self?.endRefresh()
            }
        }
        return vm
    }()
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: self.bounds, style: .plain)
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.delegate = self
        table.dataSource = self
        if self.index == 0 {
            table.register(UINib.init(nibName: kTradeUserStyleOneCell, bundle: nil), forCellReuseIdentifier: kTradeUserStyleOneCell)
        }else {
            table.register(UINib.init(nibName: kTradeUserStyleTwoCell, bundle: nil), forCellReuseIdentifier: kTradeUserStyleTwoCell)
        }
        table.themeBackground = ThemeManager.ThemeColorKeys.background
        table.themeSeparatorColor = ThemeManager.ThemeColorKeys.separator
        table.tableFooterView = UIView()
        return table
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        initData()
    }
    
    func initUI() {
        self.addSubview(tableView)
        self.tableView.mj_header = EoeRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadNewData))
        self.tableView.mj_footer = EoeRefreshFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
    }
    
    func initData() {
        if let userId = self.pageData?["userId"] as? Int {
            viewModel.addUserId(id: userId)
        }
        self.tableView.mj_footer.isHidden = true
        self.tableView.mj_header.beginRefreshing()
    }

    override func viewWillAppear() {
        super.viewWillAppear()
        
    }
    
    override func viewWillDisappear() {
        super.viewWillDisappear()
    }

    @objc func loadNewData(){
        emptyView.removeFromSuperview()
        if self.index == 0 {
            viewModel.loadNewUserAdData()
        }else {
            viewModel.loadNewUserRelatedData()
        }
    }
    
    @objc func loadMoreData(){
        emptyView.removeFromSuperview()
        if self.index == 0 {
            viewModel.loadMoreUserAdData()
        }else {
            viewModel.loadMoreUserRelatedData()
        }
    }
    
    func endRefresh() {
        self.tableView.mj_header?.endRefreshing()

        if self.index == 0 {
            if viewModel.userAdIsNoMoreData {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                
            }else {
                self.tableView.mj_footer?.endRefreshing()
                
            }
            self.tableView.mj_footer?.isHidden = viewModel.userAdList.isEmpty
            if viewModel.userAdList.isEmpty {
                emptyView.frame = self.bounds
                self.tableView.addSubview(emptyView)
            }
        }else {
            if viewModel.userRelatedIsNoMoreData {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                
            }else {
                self.tableView.mj_footer?.endRefreshing()
                
            }
            self.tableView.mj_footer?.isHidden = viewModel.userRelatedList.isEmpty
            if viewModel.userRelatedList.isEmpty {
                emptyView.frame = self.bounds
                self.tableView.addSubview(emptyView)
            }
            
        }
    }
    

}

extension UserCenterPageController: UITableViewDelegate,UITableViewDataSource {
    
    // MARK: - UITableViewDelegate UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.index == 0 {
            return self.viewModel.userAdList.count
        }
        return self.viewModel.userRelatedList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell: UITableViewCell
        if self.index == 0 {
            cell = tableView.dequeueReusableCell(withIdentifier: kTradeUserStyleOneCell, for: indexPath)
            (cell as? TradeOrderUserCenterOneCell)?.configer(model: viewModel.userAdList[indexPath.row])
        }else {
            cell = tableView.dequeueReusableCell(withIdentifier: kTradeUserStyleTwoCell, for: indexPath)
            (cell as? TradeOrderUserCenterTwoCell)?.configer(model: viewModel.userRelatedList[indexPath.row])
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if self.index == 0 {
            return 75
        }else {
            return 120
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        let nav = self.viewController()?.navigationController
        if self.index == 0 {
            let vc = BuyOrSellDetailViewController()
            let model = self.viewModel.userAdList[indexPath.row]
            if let id = model.id {
                vc.adId = id
                nav?.pushViewController(vc, animated: true)
            }else {
                CYMBShow.showMessage(kText("广告不存在"))
            }
        }else {
            let vc = ExchangeChatViewController()
            let model = self.viewModel.userRelatedList[indexPath.row]
            if let id = model.id {
                vc.orderId = id
                nav?.pushViewController(vc, animated: true)
            }else {
                CYMBShow.showMessage(kText("订单不存在"))
            }
        }
    }
}
